
import React, {Fragment} from "react";
import {Alert, Checkbox, Input, Select, Table} from 'antd';
import Store from "./Store";
import { DndProvider, DragSource, DropTarget } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import {observer} from "mobx-react";


// 拖拽排序
let dragingIndex = -1;
class BodyRow extends React.Component {
    render() {
        const { isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props;
        const style = { ...restProps.style, cursor: 'move' };

        let { className } = restProps;
        if (isOver) {
            if (restProps.index > dragingIndex) {
                className += ' drop-over-downward';
            }
            if (restProps.index < dragingIndex) {
                className += ' drop-over-upward';
            }
        }

        return connectDragSource(
            connectDropTarget(<tr {...restProps} className={className} style={style} />),
        );
    }
}

const rowSource = {
    beginDrag(props) {
        dragingIndex = props.index;
        return {
            index: props.index,
        };
    },
};

const rowTarget = {
    drop(props, monitor) {
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
            return;
        }

        // Time to actually perform the action
        props.moveRow(dragIndex, hoverIndex);

        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        monitor.getItem().index = hoverIndex;
    },
};

const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
}))(
    DragSource('row', rowSource, connect => ({
        connectDragSource: connect.dragSource(),
    }))(BodyRow),
);


@observer
class ComponentConfig extends React.Component{
    constructor(props) {
        super(props);
        this.state = {}
    }

    handleFieldChange = (key,value,field) => {
        Store.componentDataSourceMap[key][field] = value;
        Store.componentDataSource = Object.values( Store.componentDataSourceMap)
    };

    components = {
        body: {
            row: DragableBodyRow,
        },
    };

    moveRow = (dragIndex, hoverIndex) => {

        console.log("dragIndex",dragIndex)
        console.log("hoverIndex",hoverIndex)

        let data  = Store.componentDataSource;

        let dragRow = data[dragIndex];

        data.splice(dragIndex,1);

        data.splice(hoverIndex,0,dragRow);

        // eslint-disable-next-line array-callback-return
        let new_data = [];
        let new_data_map = {};
        data.forEach(item => {
            let temp = {
                component: item["component"],
                description: item["description"],
                extra: item["extra"],
                field: item["field"],
                format: item["format"],
                key: item["key"],
                must: item["must"],
            };
            new_data.push(temp);
            new_data_map[item["key"]] = temp
        });

        Store.componentDataSource = new_data;
        Store.componentDataSourceMap = new_data_map;

        console.log("new_data",new_data)
    };

    render() {
        const columns = [
            {
                title: '字段',
                dataIndex: 'field',
                key: 'field',
                width:"10%"
            },
            {
                title: '描述',
                dataIndex: 'description',
                width:"20%",
                key: 'description',
                render: (text,record) => {
                    return <Input allowClear defaultValue={text} onChange={(e) => this.handleFieldChange(record.key,e.target.value,"description")} placeholder="填写字段描述" />
                }
            },
            {
                title: '组件',
                dataIndex: 'component',
                key: 'component',
                width:"20%",
                render: (text, record) => {
                    const { Option } = Select;
                    return <Select
                        showSearch
                        onChange={(value) => {this.handleFieldChange(record.key,value,"component")}}
                        style={{width:"210px"}}
                        defaultValue={text ? text : "FormInput"}
                        optionFilterProp="children"
                    >
                        <Option value="FormInput">输入框</Option>
                        <Option value="FormMulInput">文本域</Option>
                        <Option value="FormSelect">下拉选择框</Option>
                        <Option value="FormMulSelect">下拉选择-多选</Option>
                        <Option value="FormTimePicker">时间选择器</Option>
                        <Option value="FormDatePicker">日期选择器</Option>
                        <Option value="FormMonthPicker">月份选择器</Option>
                        <Option value="FormYearPicker">年份选择器</Option>
                        <Option value="FormPointPicker">经纬度选择器</Option>
                        <Option value="FormUploadSingle">单文件上传</Option>
                        <Option value="FormUpload">多文件上传</Option>
                        <Option value="FormTimeRangePicker">时间范围选择器</Option>
                        <Option value="FormDateRangePicker">日期范围选择器</Option>
                        <Option value="FormMonthRangePicker">月份范围选择器</Option>
                        <Option value="FormYearRangePicker">年份范围选择器</Option>
                        <Option value="FormRadio">单选框</Option>
                        <Option value="FormCheckBox">多选框</Option>
                        <Option value="FormPasswordInput">密码框</Option>
                    </Select>
                }
            },
            {
                title: '格式化',
                dataIndex: 'format',
                key: 'format',
                width:"10%",
                render: (text, record) => {
                    const { Option } = Select;
                    return <Select
                        onChange={(value) => {this.handleFieldChange(record.key,value,"format")}}
                        style={{width:"210px"}}
                        defaultValue={text ? text : "text"}
                        optionFilterProp="children"
                    >
                        <Option value="text">文本</Option>
                        <Option value="pic">图片</Option>
                        <Option value="file">文件</Option>
                        <Option value="link">链接</Option>
                    </Select>
                }
            },
            {
                title: '必填',
                dataIndex: 'must',
                key: 'must',
                width:"5%",
                render: (text, record) => {
                    return <Checkbox onChange={(e) => {
                        this.handleFieldChange(record.key, e.target.checked, "must")
                    }}/>
                }
            },
            {
                title: '额外信息',
                dataIndex: 'extra',
                key: 'extra',
                width:"25%",
                render: (text,record) => {
                    return <Input allowClear defaultValue={text} onChange={(e) => this.handleFieldChange(record.key,e.target.value,"extra")} placeholder="填写额外信息" />
                }
            },
        ];
        return (
            <Fragment>
                <Alert closable showIcon type={"info"} message={"小提示"}
                       style={{width: 750,marginBottom:"10px", color: '#31708f !important'}}
                       description={"配置表单填充字段数据时的填充方式，拖拽表格行可以实现对表单展示顺序的修改。额外信息：组件是单选、多选、下拉选择时提供可选项，" +
                       "文件上传可以限制上传的文件类型，默认不受限制" }
                />
                <DndProvider backend={HTML5Backend}>
                    <Table
                        columns={columns}
                        dataSource={Store.componentDataSource}
                        pagination={false}
                        components={this.components}
                        onRow={(record, index) => ({
                            index,
                            moveRow: this.moveRow,
                        })}
                    />
                </DndProvider>
            </Fragment>
        );
    }
}

export default ComponentConfig;
